#!/usr/bin/env bash

SERVER1=$1
SERVER2=$2
SERVER3=$3
MYID=$4

echo "server.1=${SERVER1}"
echo "server.2=${SERVER2}"
echo "server.3=${SERVER3}"
echo "myid=${MYID}"

# install java 8
yum install -y java-1.8.0-openjdk-devel

# download zookeeper
curl -o apache-zookeeper-3.6.2-bin.tar.gz  https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.6.2/apache-zookeeper-3.6.2-bin.tar.gz

# extract
tar -xzf apache-zookeeper-3.6.2-bin.tar.gz -C /usr/local

mv /usr/local/apache-zookeeper-3.6.2-bin /usr/local/zookeeper

rm -f ~/apache-zookeeper-3.6.2-bin.tar.gz

groupadd zookeeper
useradd  -M -s /bin/false -g zookeeper zookeeper
echo ">>> user initiated..."

if [[ ! -d /opt/zookeeper ]]; then
        mkdir -p /opt/zookeeper
fi
echo ">>> dir initiated..."

# under {dataDir}
echo "${MYID}" >> /opt/zookeeper/myid
echo ">>> id initiated..."

chown zookeeper.zookeeper -R /usr/local/zookeeper
chmod 750 -R /usr/local/zookeeper
chown zookeeper.zookeeper -R /opt/zookeeper
chmod 750 -R /opt/zookeeper
echo ">>> privilege initiated..."
ln -s /usr/local/zookeeper /opt/zookeeper
echo ">>> link initiated..."

# run
cd /usr/local/zookeeper || exit 1

cat>/usr/local/zookeeper/conf/zoo.cfg<<EOF
tickTime=2000
dataDir=/opt/zookeeper
dataLogDir=/opt/zookeeper/logs
clientPort=2181
initLimit=10
syncLimit=5
server.1=${SERVER1}:2888:3888
server.2=${SERVER2}:2888:3888
server.3=${SERVER3}:2888:3888
EOF
echo ">>> config initiated..."

cat>/usr/lib/systemd/system/zookeeper.service<<EOF
[Unit]
Description=zookeeper
After=network.target

[Service]
User=zookeeper
Group=zookeeper
Type=forking
ExecStart=/usr/local/zookeeper/bin/zkServer.sh start
ExecReload=/usr/local/zookeeper/bin/zkServer.sh restart
ExecStop=/usr/local/zookeeper/bin/zkServer.sh stop

[Install]
WantedBy=multi-user.target
EOF
echo ">>> service initiated..."

systemctl stop firewalld

systemctl disable firewalld

systemctl enable zookeeper

systemctl start zookeeper
